package model

import (
	"github.com/jinzhu/gorm"
	"fmt"
	"os"
	"github.com/robfig/config"
)
var (
	DB_USER,
	DB_PASS,
	DB_HOST,
	DB_PORT string
)
var DB = func(dataName string)*gorm.DB{

	ApplicationDir,_:=os.Getwd()//获取项目地址
	databaseConfPath := fmt.Sprintf("%s/bin/conf/database.ini", ApplicationDir)
	c, e:= config.ReadDefault(databaseConfPath)
	if e!=nil{
		fmt.Println(e)
	}
	DB_HOST, _ := c.String(dataName,"DB_HOST")
	DB_PORT, _ := c.String(dataName, "DB_PORT")
	DB_USER, _ := c.String(dataName, "DB_USER")
	DB_PASS, _ := c.String(dataName, "DB_PASS")
	DB_NAME, _ := c.String(dataName, "DB_NAME")
	db := connect(DB_USER,DB_PASS,DB_HOST,DB_PORT,DB_NAME)
	db.SingularTable(true)
	return db;
}

func connect(DB_USER string,DB_PASS string,DB_HOST string,DB_PORT string,DB_NAME string) *gorm.DB{
	args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local",DB_USER,DB_PASS,DB_HOST,DB_PORT,DB_NAME)
	db,err:=gorm.Open("mysql",args)
	if err!=nil {
		panic("connection failure")
	}
	//defer db.Close()
	return db
}